﻿using UnityEngine;
using System.Collections;
using DG.Tweening;
/// <summary>
/// 物品的事件
/// </summary>
public class ShopItemDragCtrl : MonoBehaviour, IInputClickHandler, IInputDownHandler, IInputUpHandler, IInputDragHandler, IInputBeginDragHandler, IInputEndDragHandler
{

    Vector3 screenPos;
    Vector3 offsetDrag;


    //相机到拖拽物体的距离
    public float distanceRate = 0.3f;
    Vector3 orgPos;
    Quaternion orgRot;
    Vector3 orgScale;
    Transform orgParent;
    //是否拖拽 (判断拖拽还是点击使用)
    bool isDrag = false;


    private bool enableEvent;
    /// <summary>
    /// 启用 禁用 事件
    /// </summary>
    public bool EnableEvent
    {
        set
        {
            transform.GetComponent<BoxCollider2D>().enabled = value;
            enableEvent = value;
        }
    }

    void Start()
    {
        orgPos = transform.position;
        orgRot = transform.rotation;
        orgScale = transform.localScale;
        orgParent = transform.parent;
    }
    //是否点击UI
    //bool isClickUI = false;
    void Update()
    {
        /*if (Input.GetMouseButtonDown(0) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began))
        {
#if IPHONE || ANDROID
            if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
#else
            if (UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
#endif
            {
                //Debug.Log(" ShopItemDragCtrl  当前触摸在UI上");
                isClickUI = true;
            }
            else
            {
                //Debug.Log(" ShopItemDragCtrl  当前没有触摸在UI上");
                isClickUI = false;
            }
        }*/
    }

    public void Init()
    {

    }
    public void OnInputDown(InputEventData eventData)
    {
#if !UNITY_EDITOR && (UNITY_IOS || UNITY_ANDROID)
                if (UnityEngine.EventSystems.EventSystem.current!=null && UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
#else
        if (UnityEngine.EventSystems.EventSystem.current != null && UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
#endif
        {
            return;
        }
        //Debug.Log("  OnInputDown === " + SuperMarketGame.Instance.isCanDragScene.ToString() + "  ==  isCanDragScene)  ");
        if (!RoleInSuperMarketCtrl.Instance.isFollowCam || MarketMainSceneCtrl.Instance.isClickUI) return;
        SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.Sound_601010106);
        SuperMarketGame.Instance.DragScceneEnable(false);
    }

    public void OnInputUp(InputEventData eventData)
    {
        //在播放完动画后允许拖动场景，否则会和 SuperMarketGame  的 else if (Input.GetMouseButtonUp(0))冲突
        //SuperMarketGame.Instance.DragScceneEnable(true);
    }
    public void OnInputClick(InputEventData eventData)
    {
        //Debug.Log(RoleInSuperMarketCtrl.Instance.isCanOperateGoods.ToString() + " ==== isCanOperateGoods ");
        //Debug.Log(IsInShopList(transform.name).ToString() + "  === IsInShopList  ");
        //1 没有跟随摄像机, 2 点击了UI  3 上次挑选动作还没完成
        if (!RoleInSuperMarketCtrl.Instance.isFollowCam || MarketMainSceneCtrl.Instance.isClickUI || !RoleInSuperMarketCtrl.Instance.isCanOperateGoods) return;
        //Debug.Log("OnInputClick == "+transform.name + "  ,isDrag == "+ isDrag.ToString());
        if (isDrag) return;        
        else if (!IsInShopList(transform.name))
        {
            //sound—play
            if (PlaceGoods.Instance.goodsBuyList.Contains(name) && PlaceGoods.Instance.IsFinishBuyName(name))
            {
                //已购买的商品，玩家再次点击，出语音提示：“已经买到了”。
                SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.Sound_404050402);
            }
            else if (!PlaceGoods.Instance.goodsBuyList.Contains(name))
            {
                //购买到错误商品，乐迪语音：“不是这个，再找找看。” / “错了，不是这个哦。”
                int ran = Random.Range(0, 3);
                if (ran == 0)
                    SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.Sound_404050403);
                else if (ran == 1)
                    SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.Sound_404050404);
                else
                    SuperMarketGame.Instance.soundCtrl.PlayRoleSound(RoleSoundType.No);
            }
            //SuperMarketGame.Instance.soundCtrl.PlayRoleSound(RoleSoundType.No);
            SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.Sound_603020503);
            SuperMarketGame.Instance.SetRoleAnim(6);
        }
        else
        {
            //TODO 直接落入购物车 ,生成一个新的 ,放回去
            //Vector3 target = transform.position + transform.up * - 1.5f + transform.right + transform.forward;
            Vector3 target = SuperMarketGame.Instance.downPoint.position;
            //SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.COMMON_SOUND + "601010110");

            int num = PlaceGoods.Instance.goodsBuyDic[transform.name] + 1;
            //Debug.Log(num + "  ============ num ");
            PlaceGoods.Instance.UpdateGoodsBuyDic(transform.name, num);
            Camera.main.GetComponent<InputPhysics2DRaycaster>().eventMask = 0;
            transform.DOJump(target, 0.5f, 1, 0.8f).OnComplete(() =>
            {
                //添加到已经购买的物资里
                Camera.main.GetComponent<InputPhysics2DRaycaster>().eventMask = -1;
                OnBuyFinish();
            });
        }
        if (SuperMarketGame.Instance.guidHand)
        {
            AudioManager.Instance.StopSound(AudioManager.Instance.GetAudioClip(SuperMarketResPath.Sound_404050348));
            SuperMarketGame.Instance.guidHand = false;
            MarketMainSceneCtrl.Instance.handClick.gameObject.SetActive(false);
            MarketMainSceneCtrl.Instance.handClick.DOKill();

            if (SuperMarketGame.Instance.isFirstPlay)
                SuperMarketGame.Instance.guidTotalCount = SuperMarketGame.Instance.heartTimeCheck-2;
        }
    }


    public void OnInputBeginDrag(InputEventData eventData)
    {
#if !UNITY_EDITOR && (UNITY_IOS || UNITY_ANDROID)
                if (UnityEngine.EventSystems.EventSystem.current!=null && UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
#else
        if (UnityEngine.EventSystems.EventSystem.current != null && UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
#endif
        {
            return;
        }        
        if (!RoleInSuperMarketCtrl.Instance.isFollowCam || MarketMainSceneCtrl.Instance.isClickUI || !RoleInSuperMarketCtrl.Instance.isCanOperateGoods)
            return;

        SuperMarketGame.Instance.DragScceneEnable(false);

        isDrag = true;

        Vector3 offset = Camera.main.transform.position - transform.position;
        //Debug.Log(" offset === " + offset + "   ,TransformDirection === " + transform.TransformDirection(offset) + "   ,TransformPoint === " + transform.TransformPoint(offset));
        Vector3 dragPos = transform.position + (offset * distanceRate);

        screenPos = Camera.main.WorldToScreenPoint(dragPos);
        offsetDrag = dragPos - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPos.z));

        transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPos.z)) + offsetDrag;

        if (SuperMarketGame.Instance.guidHand)
        {
            AudioManager.Instance.StopSound(AudioManager.Instance.GetAudioClip(SuperMarketResPath.Sound_404050348));
            SuperMarketGame.Instance.guidHand = false;
            MarketMainSceneCtrl.Instance.handClick.gameObject.SetActive(false);
            MarketMainSceneCtrl.Instance.handClick.DOKill();

            if (SuperMarketGame.Instance.isFirstPlay)
                SuperMarketGame.Instance.guidTotalCount = SuperMarketGame.Instance.heartTimeCheck - 2;
        }
    }

    public void OnInputDrag(InputEventData eventData)
    {
        if (!RoleInSuperMarketCtrl.Instance.isFollowCam || MarketMainSceneCtrl.Instance.isClickUI || !RoleInSuperMarketCtrl.Instance.isCanOperateGoods) return;
        //SuperMarketGame.Instance.DragScceneEnable(false);
        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPos.z);
        Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offsetDrag;
        transform.position = curPosition;
    }


    public void OnInputEndDrag(InputEventData eventData)
    {
        if (!RoleInSuperMarketCtrl.Instance.isFollowCam || MarketMainSceneCtrl.Instance.isClickUI || !RoleInSuperMarketCtrl.Instance.isCanOperateGoods) return;
        //TODO  检测是否为需要商品， 是，入购物车，生成一个新的，旧的回原点； 否，拖回原处
        //Debug.Log(" OnInputEndDrag == " + IsInShopList(transform.name).ToString());
        isDrag = false;
        Camera.main.GetComponent<InputPhysics2DRaycaster>().eventMask = 0;
        //在播放完动画后允许拖动场景，否则会和 SuperMarketGame  的 else if (Input.GetMouseButtonUp(0))  播放的动画冲突
        //SuperMarketGame.Instance.DragScceneEnable(true);
        if (!IsInShopList(transform.name))
        {
            //sound—play
            if (PlaceGoods.Instance.goodsBuyList.Contains(name) && PlaceGoods.Instance.IsFinishBuyName(name))
            {
                //已购买的商品，玩家再次点击，出语音提示：“已经买到了”。
                SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.Sound_404050402);
            }
            else if (!PlaceGoods.Instance.goodsBuyList.Contains(name))
            {
                //购买到错误商品，乐迪语音：“不是这个，再找找看。” / “错了，不是这个哦。”
                int ran = Random.Range(0, 3);
                if (ran == 0)
                    SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.Sound_404050403);
                else if (ran == 1)
                    SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.Sound_404050404);
                else
                    SuperMarketGame.Instance.soundCtrl.PlayRoleSound(RoleSoundType.No);


            }

            //SuperMarketGame.Instance.soundCtrl.PlayRoleSound(RoleSoundType.No);
            SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.Sound_603020503);
            SuperMarketGame.Instance.SetRoleAnim(6);

            transform.DOMove(orgPos, 0.5f).OnComplete(()=> {
                Camera.main.GetComponent<InputPhysics2DRaycaster>().eventMask = -1;
            });
        }
        else
        {
            //Debug.Log("1111");
            Vector3 target = SuperMarketGame.Instance.downPoint.position;
            //SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.COMMON_SOUND + "601010110");
            int num = PlaceGoods.Instance.goodsBuyDic[transform.name] + 1;
            Debug.Log(num + "  ============ num ");
            PlaceGoods.Instance.UpdateGoodsBuyDic(transform.name, num);

            transform.DOMove(target, 0.5f).OnComplete(() =>
            {
                //Debug.Log("222222");
                //添加到已经购买的物资里   
                Camera.main.GetComponent<InputPhysics2DRaycaster>().eventMask = -1;
                OnBuyFinish();
            });
        }
    }

    void OnBuyFinish()
    {
        RoleInSuperMarketCtrl.Instance.PlayCarEffect();

        //提前移动到落入购物车之前
        /*int num = PlaceGoods.Instance.goodsBuyDic[transform.name] + 1;
        Debug.Log(num + "  ============ num ");
        PlaceGoods.Instance.UpdateGoodsBuyDic(transform.name, num);*/

        ShoppingListController.Instance.SetBuyState(transform.name, true);
        int index = 0;
        Vector3 trans = GetCarPoint(ref index);
        transform.SetParent(SuperMarketGame.Instance.putPoint);
        transform.localPosition = trans;
        //Debug.Log(" OnComplete ==  ");
        GenObj();
        //sound—play
        if (PlaceGoods.Instance.IsFinishShopping())
        {
            SuperMarketGame.Instance.DragScceneEnable(false);
            RoleInSuperMarketCtrl.Instance.isCanOperateGoods = false;
            //完成全部购物
            //SuperMarketGame.Instance.SetRoleAnim(3);
            string soundPath = Random.Range(0, 2) == 0 ? SuperMarketResPath.Sound_404050201 : SuperMarketResPath.Sound_404050406;
            SuperMarketGame.Instance.soundCtrl.PlaySoud(soundPath);
            //Debug.Log(" 完成全部购物 " + SuperMarketGame.Instance.RoleRotate);
            SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.Sound_603010706);
            MarketMainSceneCtrl.Instance.PlaySuccessEffect(true, RoleInSuperMarketCtrl.Instance.transform.position);
            SuperMarketGame.Instance.SetRoleAnim(7/*, () =>
            {

                SuperMarketGame.Instance.DragScceneEnable(false);
                //播放胜利效果  ， 切换扫码
                SuperMarketGame.Instance.SwitchScanCode();
            }*/);            
            TimerManager.Instance.AddTimer(2.5f, () => {
                //Debug.LogError("  StartCoroutine ===== ");
                //播放胜利效果  ， 切换扫码
                SuperMarketGame.Instance.SwitchScanCode();
            });
        }
        else
        {
            //完成一次购物
            SuperMarketGame.Instance.SetRoleAnim(5);
        }
        Destroy(transform.GetComponent<ShopItemDragCtrl>());
    }

    /// <summary>
    ///  在购物单里并且没有完成购买任务并且没有完成此类物品的购买
    /// </summary>
    /// <returns></returns>
    bool IsInShopList(string name)
    {
        return PlaceGoods.Instance.goodsBuyList.Contains(name) && !PlaceGoods.Instance.IsFinishBuyName(name); //&& !PlaceGoods.Instance.IsFinishShopping()
    }

    GameObject GenObj()
    {
        //Debug.Log("  GenObj === " + gameObject.name);
        GameObject go = Instantiate(gameObject);
        go.name = transform.name;
        go.transform.SetParent(orgParent);
        go.transform.position = orgPos;
        go.transform.rotation = orgRot;
        go.transform.localScale = orgScale;
        return go;
    }

    /// <summary>
    /// 获取购物车的存放购买物品坐标 (目前仅支持三个点 按顺序排放 ) == 修改为最多可支持 5排3列 15 种商品
    /// </summary>
    /// <returns></returns>
    Vector3 GetCarPoint(ref int index)
    {
        //购物车  放置物品位置  从0 开始  0 1 2  
        /* 0.1,0.26,0.08;  -0.02,0.24,0.08;  -0.14,0.24,0.08;     X : -0.12    Y :0.04   Z -0.04
                0.30 0.04
                0.34 0
                0.38 -0.04
                0.42 -0.08
        */
        float x = 0, y = 0, z = 0;
        index = SuperMarketGame.Instance.putPoint.childCount;
        int tempPopX = index % 3;
        x = -0.12f * tempPopX + 0.1f;
        int tempPopY = index / 3;
        y = 0.04f * tempPopY + 0.28f;
        z = -0.04f * tempPopY + 0.08f;
        //Debug.Log(new Vector3(x, y, z) + "  == GetCarPoint, index == "+ index);
        //Transform[] trans = { SuperMarketGame.Instance.putPoint1, SuperMarketGame.Instance.putPoint2, SuperMarketGame.Instance.putPoint3 };        
        //index = SuperMarketGame.Instance.putPoint1.childCount + SuperMarketGame.Instance.putPoint2.childCount + SuperMarketGame.Instance.putPoint3.childCount;
        //当前放到坑里的数量，找到应该放入坑的index
        //return trans[index];
        return new Vector3(x, y, z);
    }


}
